package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.EmpDao;
import entity.Emp;
import org.thymeleaf.context.Context;
import utils.R;
import utils.ThUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UpdateServlet",urlPatterns = "/update")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        String ids = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String mobile = request.getParameter("mobile");
        String email = request.getParameter("email");

        if(ids!=null){
            Integer id = Integer.parseInt(ids);
            System.out.println("id="+id);
            Context context = new Context();
            EmpDao empDao=new EmpDao();
            Emp emp = empDao.findById(id);
            emp.setEmail(email);
            emp.setMobile(mobile);
            emp.setPassword(password);
            emp.setUsername(username);
           /* context.setVariable("emp",emp);
            ThUtils.print("edit.html",context,response);
            response.sendRedirect(request.getContextPath()+"/emplist");
            */
            Integer row = empDao.update(emp);
            R json = new R();
            if(row==1){
                json.setState(1);
                /*json.setMessage("");*/
            }else{
                json.setMessage("更新失败");
            }
            //把得到的集合转成json字符串
            ObjectMapper om = new ObjectMapper();
            String result = om.writeValueAsString(json);
            //把json字符串返回给客户端   text/html 表示返回的数据是文本或标签
            //application/json告诉客户端返回的是Json对象 客户端接收到数据时不需要再进行转换
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.print(result);
            pw.close();

        }
    }
}
